package com.hs.srm.admin.modules.inforecord.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hs.srm.admin.modules.inforecord.entity.InforecordEntity;
import com.hs.srm.admin.modules.inforecord.entity.InforecordLogEntity;
import com.hs.srm.admin.modules.inforecord.service.InforecordService;
import com.hs.srm.admin.modules.inforecord.service.SupplyGoodService;
import com.hs.srm.admin.modules.inforecord.service.impl.InforecordLogService;
import com.hs.srm.admin.modules.sequence.service.SequenceService;
import com.hs.srm.admin.modules.sys.controller.AbstractController;
import com.hs.srm.base.common.annotation.SysLog;
import com.hs.srm.base.common.config.SysConfig;
import com.hs.srm.base.common.utils.DictDataUtil;
import com.hs.srm.base.common.utils.EntityUtils;
import com.hs.srm.base.modules.sys.entity.SysUserEntity;
import com.hs.srm.common.utils.*;
import com.sap.conn.jco.*;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@RestController
@RequestMapping("/inforecord")
public class InforecordController extends AbstractController {

    /**
     * 类序列ID
     */
    private static final long serialVersionUID = -2392337998173025326L;

    @Autowired
    private InforecordService inforecordService;

    @Autowired
    private SupplyGoodService supplyGoodServiceImpl;

    @Autowired
    private SequenceService sequenceService;
    @Autowired
    private InforecordLogService inforecordLogService;

    /**
     * 查询列表
     */
    @RequestMapping("/list")
    @ResponseBody
    public R list(@RequestParam Map<String, Object> params) {
        PageUtils pu = this.inforecordService.queryPage(params);
        List<InforecordEntity> list = (List<InforecordEntity>) pu.getList();
        list = EntityUtils.valToTxt(list);
        pu.setList(list);
        return R.ok(pu);
    }


    /**
     * @Description 信息记录编辑
     * @Param []
     * @Return org.springframework.web.servlet.ModelAndView
     * @Author socik
     * @Date 2019/5/27 11:55
     */
    @RequestMapping("/toEdit/{pkId}")
    public ModelAndView toEdit(@PathVariable("pkId") String pkId) {
        InforecordEntity inforecordEntity = this.inforecordService.selectById(pkId);
        // 把查询出来的对象赋值给物料信息实体
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/inforecord_edit");
        modelAndView.addObject("inforecordEntity", inforecordEntity);
        return modelAndView;
    }

    /**
     * 信息记录修改
     *
     * @param pkId
     * @return
     */
    @SysLog("信息记录修改")
    @RequestMapping("/toUpdate/{pkId}")
    public ModelAndView toUpdate(@PathVariable("pkId") String pkId) {
        InforecordEntity inforecordEntity = this.inforecordService.selectById(pkId);
        // 把查询出来的对象赋值给物料信息实体
        ModelAndView modelAndView = new ModelAndView("modules/inforecord/inforecord_update");
        modelAndView.addObject("inforecord", inforecordEntity);
        return modelAndView;
    }

    /**
     * 信息记录编辑
     */
    @SysLog("编辑信息记录")
    @RequestMapping("/update")
    public R updateInfoRecord(InforecordEntity inforecord) {
        InforecordEntity inforecordEntity = this.inforecordService.selectById(inforecord.getPkId());
        inforecordEntity.setPrice(inforecord.getPrice());
        inforecordEntity.setCycle(inforecord.getCycle());
        inforecordEntity.setStartData(inforecord.getStartData());
        inforecordEntity.setStandardNum(inforecord.getStandardNum());
        inforecordEntity.setPurchaseUnit(inforecord.getPurchaseUnit());
        inforecordEntity.setPriceUnit(inforecord.getPriceUnit());
        inforecordEntity.setPurchaseGroup(inforecord.getPurchaseGroup());
        inforecordEntity.setClassify(inforecord.getClassify());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = "9999-12-31";
        Date date = new Date();
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        inforecordEntity.setPriceEndData(date);
        //isync:是否同步,1 点价不同步sap
        if (inforecordEntity.getIsync() == 1) {
            inforecordEntity.setInfoStatus(1);
        }
        this.inforecordService.updateById(inforecordEntity);
        return R.ok();
    }

    /**
     * 采购确认信息记录，同步数据到sap
     *
     * @param pkId
     * @return
     */
    @SysLog("信息记录确认")
    @RequestMapping("/confirmInfo/{pkId}")
    public R confirmInfo(@PathVariable("pkId") String[] pkId) {
        List<InforecordEntity> infoRecordList = this.inforecordService.selectBatchIds(Arrays.asList(pkId));
        InforecordLogEntity inforecordLogEntity = new InforecordLogEntity();
        JCoDestination destination = null;
        JCoFunction function = null;
        JCoParameterList importList = null;
        JCoParameterList tables = null;
        try {
            destination = JCoDestinationManager.getDestination("IDOC_AFS");
            function = destination.getRepository().getFunction("ZFM_SRM_INFORECORD_CRE_AND_CHA");
            importList = function.getImportParameterList();
            tables = function.getTableParameterList();

        } catch (JCoException e) {
            e.printStackTrace();
        }

        for (InforecordEntity inforecordEntity : infoRecordList) {
            //已确认状态
            inforecordEntity.setInfoStatus(1);
            DozerUtil.map(inforecordEntity, inforecordLogEntity);
            inforecordLogEntity.setSapOrSrm("srm");
            //信息记录不空，则表示为修改
            if (StringUtils.isNotBlank(inforecordEntity.getInfoCode())) {
                importList.setValue("OP_MODE", "U");
                inforecordLogEntity.setFlag(0);
            } else {
                //传入创建标识I
                importList.setValue("OP_MODE", "I");
                inforecordLogEntity.setFlag(1);
            }
            //信息记录类别：S，标准(1)；O，外协(3)
            if (inforecordEntity.getClassify().equals("0")) {
                importList.setValue("OP_TYPE", "S");
            } else {
                importList.setValue("OP_TYPE", "O");
            }
            JCoTable importTable = tables.getTable("IN_TAB");
            importTable.appendRow();
            //物料号
            importTable.setValue("MATNR", "0000000000" + inforecordEntity.getMaterialCode());
            //供应商代码
            importTable.setValue("LIFNR", inforecordEntity.getSrmCode());
            //采购组织
            importTable.setValue("EKORG", "1000");
            //采购订单基本计量单位
            importTable.setValue("MEINS", inforecordEntity.getPurchaseUnit());
            if (inforecordEntity.getCurrency().equals("JPY") || inforecordEntity.getCurrency().equals("THB")) {
                importTable.setValue("NETPR", inforecordEntity.getPrice().intValue());
            } else {
                //净价
                importTable.setValue("NETPR", inforecordEntity.getPrice().doubleValue());
            }
            //订单价格单位
            importTable.setValue("PEINH", inforecordEntity.getPriceUnit());
            //定价单位
            importTable.setValue("UMREZ", "1");
            //定价单位
            importTable.setValue("UMREN", "1");
            //税代码
            importTable.setValue("MWSKZ", inforecordEntity.getTaxCode());
            //采购组
            importTable.setValue("EKGRP", inforecordEntity.getPurchaseGroup());
            //价格单位
            importTable.setValue("WAERS", inforecordEntity.getCurrency());
            //有效起始日期
            importTable.setValue("DATAB", DateUtils.format(inforecordEntity.getStartData(), DateUtils.DATE_TIME_ALL_SAP));
            //有效截至日期 99991231
            importTable.setValue("DATBI", DateUtils.format(inforecordEntity.getPriceEndData(), DateUtils.DATE_TIME_ALL_SAP));
            //订单价格转换
            importTable.setValue("BPUMZ", "1");
            //订单价格转换
            importTable.setValue("BPUMN", "1");
            //基本单位
            String dw = DictDataUtil.valToTxt(inforecordEntity.getPurchaseUnit(), DictDataUtil.DictType.JLDW);
            if (dw != null) {
                //截取订单单位
                dw = dw.substring(dw.indexOf("_") + 1);
            } else {
                dw = " ";
            }
            importTable.setValue("MEINS", dw);
            //周期
            importTable.setValue("APLFZ", String.valueOf(inforecordEntity.getCycle()));
            //标准数量
            importTable.setValue("NORBM", String.valueOf(inforecordEntity.getStandardNum()));
            //订单价格单位（采购）
            importTable.setValue("BPRME", dw);
            try {
                function.execute(destination);
            } catch (JCoException e) {
                e.printStackTrace();
            }
            JCoTable returnTable = tables.getTable("OUT_TAB");
            String msg = returnTable.getValue("MESSAGE") + "";
            String type = returnTable.getValue("ZTYPE") + "";
            if ("S".equals(type) && msg != null && msg != "") {
                if (!"失败".equals(msg)) {
                    msg = msg.substring(0, msg.indexOf(" "));
                }
                String regEx = "[^0-9]";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(msg);
                inforecordEntity.setInfoCode(m.replaceAll("").trim());
                inforecordLogEntity.setInfoCode(inforecordEntity.getInfoCode());
                inforecordLogEntity.setCreatetime(new Date());
                inforecordLogEntity.setUpdateUser(this.getUser().getUsername());
                this.inforecordLogService.insert(inforecordLogEntity);
                this.inforecordService.updateById(inforecordEntity);
            } else {
                return R.error(msg);
            }
        }
        return R.ok();
    }


    /**
     * 获取未确认的信息记录数
     * infoRecord:confirmInfo:拥有该权限的用户才可访问
     */
    @GetMapping("/getConfirmCount")
    @RequiresPermissions("infoRecord:confirmInfo")
    public R getConfirmCount() {
        //查找未确认的信息记录数
        // info_status：信息记录状态：0，未确认；1，已确认
        int count = inforecordService.selectCount(new EntityWrapper<InforecordEntity>()
                .eq("info_status", 0));
        return R.ok(count);
    }

    /**
     * @Description 信息记录保存
     * @Param []
     * @Author socik
     * @Date 2019/5/27 11:55
     */
    @SysLog("信息记录保存")
    @RequestMapping("/save")
    public R save(InforecordEntity inforecordEntity) {
        SysUserEntity username = this.getUser();
        inforecordEntity.setMaterialCode(inforecordEntity.getMaterialCode().trim());
        inforecordEntity.setSrmCode(inforecordEntity.getSrmCode().trim());
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String time = "9999-12-31";
        Date date = new Date();
        try {
            date = dateFormat.parse(time);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        inforecordEntity.setPriceEndData(date);
        boolean inforecordEntity1 = this.inforecordService.checkRecordFrominfo(inforecordEntity.getMaterialCode(), inforecordEntity.getWerks(), inforecordEntity.getSrmCode());
        if (!inforecordEntity1) {
            this.inforecordService.insert(inforecordEntity);
        } else {
            return R.error("该信息记录已经存在!");
        }
        return R.ok();
    }

    /**
     * 冻结或者解冻
     *
     * @param pkId
     * @return
     */
    @SysLog("冻结/解冻")
    @RequestMapping("/freezeorthraw/{pkId}")
    public R changeStatus(@PathVariable(value = "pkId") String pkId) {
        InforecordEntity inforecordEntity = inforecordService.selectById(pkId);
        Integer freeze1 = inforecordEntity.getFreeze();
        if (freeze1 == 0) {
            inforecordEntity.setFreeze(1);
        } else {
            inforecordEntity.setFreeze(0);
        }
        inforecordService.updateById(inforecordEntity);
        return R.ok();
    }

    @SysLog("修改价格/有效期")
    @PostMapping("/updatePriceDate")
    public R updatePriceDate(InforecordEntity infoRecord) {
        InforecordEntity inforecordEntity = this.inforecordService.selectById(infoRecord.getPkId());
        inforecordEntity.setPrice(infoRecord.getPrice());
        inforecordEntity.setPriceUnit(infoRecord.getPriceUnit());
        inforecordEntity.setPurchaseGroup(infoRecord.getPurchaseGroup());
        inforecordEntity.setStartData(infoRecord.getStartData());
        inforecordEntity.setPriceEndData(infoRecord.getPriceEndData());
        //信息记录编号不空，表示非点价的，需要同步SAP
        if (StringUtils.isNotBlank(inforecordEntity.getInfoCode())) {
            inforecordEntity.setInfoStatus(0);
        }
        inforecordService.updateById(inforecordEntity);
        return R.ok();
    }

    /**
     * 用Excel批量导入供应商的信息
     */
    @SysLog("导入供应商的信息")
    @RequestMapping("/imp")
    // @RequiresPermissions("vendor:imp")
    public R impXls(@RequestParam("xlsFile") MultipartFile xlsFile) {
        File baseDir = new File(SysConfig.getUploadPath());
        if (!baseDir.exists() || !baseDir.isDirectory()) {
            baseDir.mkdirs();
        }
        String path = SysConfig.getUploadPath() + File.separator + System.currentTimeMillis()
                + xlsFile.getOriginalFilename();
        File savedFile = new File(path);
        try {
            xlsFile.transferTo(savedFile);
        } catch (Exception ex) {
            return R.error(Constants.ImpResultMsg.UPLOAD_FILE_FAILURE);
        }
        try {
            Map<String, Object> errorMsg = this.inforecordService.importData(savedFile, this.getUser().getUsername());
            if (errorMsg.isEmpty()) {
                return R.ok();
            }
            return (errorMsg.get("err") == null) ? R.error() : R.error(errorMsg.get("err").toString());
        } catch (Exception ex) {
            ex.printStackTrace();
            return R.error(Constants.ImpResultMsg.IMPORT_DATA_FAILURE);
        } finally {
            savedFile.delete();// 导入完成后不管是否成功，都将文件删除
        }
    }


    /**
     * 保存用Excel批量导入信息记录
     */
    @SysLog("导入信息信息记录")
    @RequestMapping("/saveImp")
    // @RequiresPermissions("vendor:imp")
    public R saveImp() {
        int impCount = this.inforecordService.saveImp();
        return R.ok().put("impCount", Integer.valueOf(impCount));
    }


    /**
     * 取消确认
     *
     * @param pkId
     * @return
     */
    @SysLog("取消确认")
    @RequestMapping("/unconfirmInfo/{pkId}")
    public R unconfirmInfo(@PathVariable(value = "pkId") String pkId) {
        InforecordEntity inforecordEntity = inforecordService.selectById(pkId);
        inforecordEntity.setInfoStatus(0);
        inforecordService.updateById(inforecordEntity);
        return R.ok();
    }
}
